package com.glorysoft.wangnianxinpda.utils;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;
import android.widget.Toast;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created by LongQ on 2018/1/22.
 */

public class FileUtils {

    /**
     * 从txt文件获取数据
     *
     * @return
     */
    public static ResultSet readJson(Context context, String sFileName) {
        ResultSet rResultSet = new ResultSet<String>();
        StringBuilder builder = null;
        try {
            InputStreamReader isr = new InputStreamReader(context.getAssets().open(sFileName), "UTF-8");
            BufferedReader br = new BufferedReader(isr);
            String line;
            builder = new StringBuilder();
            while ((line = br.readLine()) != null) {
                builder.append(line);
            }
            br.close();
            isr.close();

            rResultSet.setStatus(0);
            rResultSet.setMsg("OK");
            rResultSet.setData(builder.toString());
        } catch (Exception e) {
            e.printStackTrace();
            rResultSet.setStatus(-1);
            rResultSet.setMsg("NG");
        }
        return rResultSet;
    }

    /**
     * 创建单个文件
     *
     * @param context
     * @param filePath
     * @param fileName
     * @return
     */
    public File createFile(Context context, String filePath, String fileName) {
        File mFile = null;
        createDir(context, filePath);// 生成文件夹
        try {
            mFile = new File(filePath + fileName);
            //判断文件是否存在，存在就删除
            if (mFile.exists()) {
                mFile.delete();
            }
            //创建文件
            mFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
            ToastUtil.showShortToast(context, "文件创建失败!" + e.getMessage());
        }
        return mFile;
    }

    /**
     * 创建文件夹
     *
     * @param context
     * @param filePath
     */
    public static void createDir(Context context, String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            //判断文件夹是否存在，如果不存在就创建，否则不创建
            if (!file.exists()) {
                //通过file的mkdirs()方法创建目录中包含却不存在的文件夹
                file.mkdirs();
            }
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.showShortToast(context, "文件夹创建失败!" + e.getMessage());
        }
    }

    //判断是否有SD卡
    public static boolean existSDCard() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else
            return false;
    }

    //读取文件内容
    public static String readFile(String sFileName) {
        String sMag = "";
        String data = "";
        String sImei = "";
        String sMac = "";
        String sRegistrationCode = "";
        if (TextUtils.isEmpty(sFileName)) {
            sMag = "本地注册文件目录不能为空！";
            return sMag;
        }
        final StringBuffer sDest = new StringBuffer();
        final File file = new File(sFileName);
        //判断本地注册文件是否存在
        if (!file.exists()) {
            sMag = "本地注册文件内容为空！";
            return sMag;
        }
        try {
            FileInputStream is = new FileInputStream(file);
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            try {

                //                while ((data = br.readLine()) != null) {
                //                    sDest.append(data);
                //                }
                while ((data = br.readLine()) != null) {
                    data.trim();
                    //END(每组数据结束标识)
                    if (data.startsWith("END")) {
                        if (sImei.equals("")) {
                            sMag = "IMEI号不能为空！";
                            return sMag;
                        }
                        if (sMac.equals("")) {
                            sMag = "MAC地址不能为空！";
                            return sMag;
                        }
                        if (sRegistrationCode.equals("")) {
                            sMag = "注册码不能为空！";
                            return sMag;
                        }
                        break;
                    }

                    //MEI
                    if (data.startsWith("sImei")) { //确定此字符串开头是否与指定的字符串匹配
                        sImei = data.substring(data.indexOf("=") + 1).trim();
                        if (sImei.equals("")) {
                            sMag = "IMEI号不能为空！";
                            return sMag;
                        }
                        continue;
                    }

                    //MAC
                    if (data.startsWith("sMac")) {
                        sMac = data.substring(data.indexOf("=") + 1).trim();
                        if (sMac.equals("")) {
                            sMag = "MAC地址不能为空！";
                            return sMag;
                        }
                        continue;
                    }

                    //注册码
                    if (data.startsWith("sRegistrationCode")) {
                        sRegistrationCode = data.substring(data.indexOf("=") + 1).trim();
                        if (sRegistrationCode.equals("")) {
                            sMag = "注册码不能为空！";
                            return sMag;
                        }
                        continue;
                    }
                }
            } catch (IOException ioex) {

            } finally {
                is.close();
                is = null;
                br.close();
                br = null;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return ex.getMessage();
        } catch (OutOfMemoryError oe) {
            oe.printStackTrace();
            return oe.getMessage();
        }
        return sRegistrationCode;
    }

    //读取PDF文件
    public static void readPdf(Context context, String path) {
        if (existSDCard()) {
            File file = new File(Environment.getExternalStorageDirectory() + path);
            openPDFReader(context, file);
        }
    }

    //调用第三方软件打开PDF文件
    public static void openPDFReader(Context context, File file) {
        if (file.exists()) {
            Uri path = Uri.fromFile(file);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(path, "application/pdf");
            try {
                context.startActivity(intent);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(context,
                        "No Application Available to View PDF",
                        Toast.LENGTH_SHORT).show();
            }
        }
    }

    //判断SD卡剩余空间
    public static long getSDFreeSize() {
        if (existSDCard()) {
            //取得SD卡文件路径
            File path = Environment.getExternalStorageDirectory();
            StatFs sf = new StatFs(path.getPath());
            //获取单个数据块的大小(Byte)
            long blockSize = sf.getBlockSize();
            //空闲的数据块的数量
            long freeBlocks = sf.getAvailableBlocks();
            //返回SD卡空闲大小
            //return freeBlocks * blockSize;  //单位Byte
            //return (freeBlocks * blockSize)/1024;   //单位KB
            return (freeBlocks * blockSize) / 1024 / 1024; //单位MB
        }
        return 0;
    }

    //判断SD卡总容量
    public static long getSDAllSize() {
        if (existSDCard()) {
            //取得SD卡文件路径
            File path = Environment.getExternalStorageDirectory();
            StatFs sf = new StatFs(path.getPath());
            //获取单个数据块的大小(Byte)
            long blockSize = sf.getBlockSize();
            //获取所有数据块数
            long allBlocks = sf.getBlockCount();
            //返回SD卡大小
            //return allBlocks * blockSize; //单位Byte
            //return (allBlocks * blockSize)/1024; //单位KB
            return (allBlocks * blockSize) / 1024 / 1024; //单位MB
        }
        return 0;
    }

    //删除文件
    public static void delFile(String path) {
        if (existSDCard()) {
            File file = new File(Environment.getExternalStorageDirectory() + path);
            //是否存在
            if (file.exists()) {
                file.delete();
            }
        }

    }
}
